package com.qianniu.napi.admin.web;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;

import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.jsmodel.Template;
import com.qianniu.napi.admin.entity.jsmodel.TemplateParam;
import com.qianniu.napi.admin.service.IOrderService;
import com.qianniu.napi.admin.service.ITemplatemsgService;
import com.qianniu.napi.admin.service.ITplformService;

import com.qianniu.napi.admin.service.IUserService;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.helper.HttpHelper;
import com.qianniu.napi.common.util.EncryptUtil;
import com.qianniu.napi.common.util.ObjectUtil;
import com.qianniu.napi.common.util.WeixinUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * <p>
 *
 * </p>
 *
 * @author chenxuebin
 * @since 2019-03-11
 */
@Controller
public class TplformController {

    private static final Logger logger = LoggerFactory.getLogger(TplformController.class);

    @Autowired
    private ITplformService tplformService;
    @Autowired
    private ITemplatemsgService templatemsgService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IUserService userService;

    @RequestMapping("admin/tplform/index")
    public String index() {
        return "admin/tplform";
    }

    @RequestMapping("/admin/tplform/list")
    @ResponseBody
    public Page<Tplform> list(@RequestParam(value = "offset", required = false) Integer offset,
                              @RequestParam(value = "status", required = false) Integer status,
                              @RequestParam(value = "search", required = false) String search,
                              @RequestParam(value = "limit", required = false) Integer limit) {
        Wrapper<Tplform> wrapper = new EntityWrapper<Tplform>();
        wrapper.eq("mpid", ObjectUtil.getMpid());
//        if (!Strings.isNullOrEmpty(search))
//            wrapper.like("order_no", search).or().like("remark", search);

        wrapper.orderBy("id", false);
        Page<Tplform> page = tplformService.selectPage(new Page<Tplform>(offset / limit + 1, limit), wrapper);
        return page;
    }

    @RequestMapping("/admin/tplform/add")
    public String add(@Valid Tplform bean, BindingResult bindingResult) {
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            return null;
        }
        bean.setCreatetime(new Date());
        bean.setUid(ObjectUtil.getUid());
        bean.setMid(ObjectUtil.getMid());
        bean.setMpid(ObjectUtil.getMpid());
        bean.insert();
        return "admin/tplform";
    }

    @RequestMapping("/admin/tplform/getTplformById")
    @ResponseBody
    public Tplform getTplformById(long id) {
        Tplform tplform = tplformService.selectById(id);
        return tplform;
    }

    @RequestMapping("/admin/tplform/deleteOne")
    @ResponseBody
    public int deleteOne(long id) {
        boolean isSucc = tplformService.deleteById(id);
        return isSucc ? 1 : 0;
    }

    @RequestMapping("/admin/tplform/changeState")
    @ResponseBody
    public Jinfo changeState(long id) {
        Jinfo info = new Jinfo();
        Tplform bean = tplformService.selectById(id);
        if (bean == null) {
            info.setCode(1);
            return info;
        }
        Templatemsg tplmsg = templatemsgService.selectOne(new EntityWrapper<Templatemsg>().eq("tplid", bean.getFormid()));
        if (tplmsg == null) {
            info.setCode(1);
            return info;
        }

        Template template = new Template();
        template.setTemplate_id(tplmsg.getTplid());
        template.setTouser(bean.getOpenid());
        template.setPage(tplmsg.getPage());

        Order order = orderService.selectOne(new EntityWrapper<Order>().eq("order_no", bean.getOrderno()));
        String sname = order.getSname();
        sname = sname.length()>20?sname.substring(0,20):sname;
        String gname = order.getGoodsName();
        gname = gname.length()>20?gname.substring(0,20):gname;
        String typename = order.getType()==1?"拼团活动":order.getType()==1?"砍价活动":order.getType()==1?"抽检活动":
                order.getType()==7?"大礼包活动":order.getType()==8?"秒杀活动":order.getType()==9?"报名活动":
                        order.getType()==10?"投票活动":order.getType()==13?"集赞活动":"砍价活动";
        String addr = order.getAddress()==null?"":order.getAddress();
        addr = addr.length()>20?addr.substring(0,20):addr;

        List<TemplateParam> paras = new ArrayList<TemplateParam>();
        for (int i = 1; i <= tplmsg.getKeysize(); i++) {
            if (tplmsg.getTplcode().equals("daotianziti")) {
                //到点自提
//                商品名称 {{thing1.DATA}}
//                提货门店 {{thing2.DATA}}
//                门店地址 {{thing3.DATA}}
//                联系电话 {{phone_number4.DATA}}
//                温馨提示 {{thing6.DATA}}
                if (order == null) {
                    info.setCode(1);
                    return info;
                }

                if (i == 1) paras.add(new TemplateParam(tplmsg.getKeycode1(), gname));
                if (i == 2) paras.add(new TemplateParam(tplmsg.getKeycode2(), sname));
                if (i == 3) paras.add(new TemplateParam(tplmsg.getKeycode3(), addr));
                if (i == 4) paras.add(new TemplateParam(tplmsg.getKeycode4(), order.getPhone()));
                if (i == 5) paras.add(new TemplateParam(tplmsg.getKeycode5(), "请点击查看详情"));

            } else if (tplmsg.getTplcode().equals("wenzhentixing")) {
//                问诊内容 {{thing1.DATA}}
//                提醒内容 {{thing2.DATA}}
//                问诊医生 {{name3.DATA}}
//                提示说明 {{thing4.DATA}}
                if (i == 1) paras.add(new TemplateParam(tplmsg.getKeycode1(), "您好，请问现在口腔问题怎么样了"));
                if (i == 2) paras.add(new TemplateParam(tplmsg.getKeycode2(), "如有出现不适，请尽早到门诊来检查"));

                User user = userService.selectOne(new EntityWrapper<User>().eq("sid",order.getSid())
                        .eq("is_mch",1).eq("is_admin",1));

                if (i == 3) paras.add(new TemplateParam(tplmsg.getKeycode3(),user.getNickName()));
                if (i == 4) paras.add(new TemplateParam(tplmsg.getKeycode4(), "您可以在微信中直接回复医生"));
                String page = tplmsg.getPage();
                page+="?sid="+order.getSid();
                template.setPage(page);
            } else if (tplmsg.getTplcode().equals("xinhdtongzhi")) {
//                商家名称 {{thing1.DATA}}
//                活动名称 {{thing2.DATA}}
//                活动类型 {{phrase3.DATA}}
//                商品价格 {{amount4.DATA}}
//                温馨提示 {{thing7.DATA}}

                if (i == 1) paras.add(new TemplateParam(tplmsg.getKeycode1(), sname));
                if (i == 2) paras.add(new TemplateParam(tplmsg.getKeycode2(), gname));
                if (i == 3) paras.add(new TemplateParam(tplmsg.getKeycode3(), typename));
                if (i == 4) paras.add(new TemplateParam(tplmsg.getKeycode4(), order.getTotal().toString()));
                if (i == 5) paras.add(new TemplateParam(tplmsg.getKeycode5(), "请进入小程序查看"));

            } else if (tplmsg.getTplcode().equals("")) {
//                问诊内容 {{thing1.DATA}}
//                提醒内容 {{thing2.DATA}}
//                问诊医生 {{name3.DATA}}
//                提示说明 {{thing4.DATA}}

                if (i == 1) paras.add(new TemplateParam(tplmsg.getKeycode1(), "000001"));
                if (i == 2) paras.add(new TemplateParam(tplmsg.getKeycode2(), "888.88"));
                if (i == 3) paras.add(new TemplateParam(tplmsg.getKeycode3(), "2015年01月05日"));
                if (i == 4) paras.add(new TemplateParam(tplmsg.getKeycode4(), "请进入小程序查1看"));
                if (i == 5) paras.add(new TemplateParam(tplmsg.getKeycode5(), "请进入小程序查1看"));
            }
        }

        template.setTemplateParamList(paras);
        logger.debug("========================template.toJSON()="+template.toJSON());
        WeixinUtil.sendDingyueMsg(order.getMpid().toString(),template.toJSON());

        Tplform nbean = new Tplform();
        nbean.setId(id);
        if(bean.getIsonce()==1)nbean.setState(-1);
        nbean.setIsuse(bean.getIsuse()+1);
        nbean.setModifytime(new Date());
        nbean.updateById();

        return info;
    }

    @RequestMapping("/admin/tplform/modify")
    public String update(Tplform bean) {
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        boolean isSuccc = tplformService.updateById(bean);
        if (isSuccc) {
            return "redirect:index";
        }
        return "error";
    }

}
